
package net.swa.dewei.thread;

import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;
import net.sf.json.JSONObject;
import net.swa.dewei.beans.entity.WeixinInfo;
import net.swa.util.BuzConst;
import net.swa.util.DateUtils;
import net.swa.util.FileUtil;
import net.swa.util.MySecureProtocolSocketFactory;
import net.swa.util.StringUtil;

/***
 * 查询微信详细信息操作类
 * @author dawei
 *
 */
public class SynWxInfoThread extends Thread
{
    private final Logger log = Logger.getLogger(SynWxInfoThread.class);

    private static List<Thread> runningThreads = new ArrayList<Thread>();

    private static int c;

    private static int total;

    private String token;

    private String openId;

    private Session currentSession;

    @SuppressWarnings("static-access")
    public SynWxInfoThread(String token, String openId, Session currentSession, int total)
    {
        if (log.isDebugEnabled())
        {
            log.debug("创建线程");
        }
        this.token = token;
        this.openId = openId;
        this.currentSession = currentSession;
        this.total = total;
    }

    public void run()
    {
        regist(this);//线程开始时注册
        try
        {
            work();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        unRegist(this);
    }

    public void work()
    {
        Transaction tx = null;
        try
        {
            WeixinInfo wx = new WeixinInfo();
            wx.setId(openId);
            String nickname = null;
            String http = BuzConst.HTTP_WX_USER_INFO + "?access_token=" + token + "&openid=" + openId;
            String resp;
            resp = MySecureProtocolSocketFactory.get(http);
            JSONObject jsonObj = JSONObject.fromObject(resp.toString());
            if (log.isDebugEnabled())
            {
                log.debug("线程开始执行。。。线程名：" + Thread.currentThread().getName());
                log.debug("同步数据：" +resp);
            }
            if (null != jsonObj)
            {
                if (null != jsonObj.get("nickname"))
                {
                    nickname = jsonObj.get("nickname").toString();
                    nickname = StringUtil.filterStr(nickname);
                    wx.setNickname(nickname);
                }
                if (null != jsonObj.get("province"))
                {
                    String province = jsonObj.get("province").toString();

                    wx.setProvince(province);
                }

                if (null != jsonObj.get("city"))
                {
                    String city = jsonObj.get("city").toString();
                    wx.setCity(city);
                }

                if (null != jsonObj.get("headimgurl"))
                {
                    String headimgurl = jsonObj.get("headimgurl").toString();
                    wx.setHeadimgurl(headimgurl);
                    if (headimgurl.length() > 0)
                    {
                        wx.setSheadimgurl("data:image/png;base64," + FileUtil.imageToBase64(headimgurl.substring(0, headimgurl.length() - 1) + "64"));
                    }
                }

                if (null != jsonObj.get("subscribe"))
                {
                    String subscribe = jsonObj.get("subscribe").toString();
                    wx.setSubscribe(subscribe);
                }

                if (null != jsonObj.get("sex"))
                {
                    String sex = jsonObj.get("sex").toString();
                    wx.setSex(sex);
                }

                if (null != jsonObj.get("language"))
                {
                    String language = jsonObj.get("language").toString();
                    wx.setLanguage(language);
                }

                if (null != jsonObj.get("country"))
                {
                    String country = jsonObj.get("country").toString();
                    wx.setCountry(country);
                }
                if (null != jsonObj.get("subscribe_time"))
                {
                    String subscribe_time = jsonObj.get("subscribe_time").toString();
                    wx.setSubscribe_time(subscribe_time);
                }
            }
            wx.setStatus(BuzConst.WX_GUANZHU);
            WeixinInfo m = (WeixinInfo) currentSession.get(WeixinInfo.class, openId);
            tx = currentSession.beginTransaction();
            if (null == m)
            {
                wx.setUpdateTime(DateUtils.getCurrDate(null));
                wx.setGuazhuTime(DateUtils.getCurrDate(null));
                currentSession.save(wx);
            }
            else
            {
                m.setCity(wx.getCity());
                m.setProvince(wx.getProvince());
                m.setHeadimgurl(wx.getHeadimgurl());
                m.setLanguage(wx.getLanguage());
                m.setNickname(wx.getNickname());
                m.setProvince(wx.getProvince());
                m.setSex(wx.getSex());
                m.setSheadimgurl(wx.getSheadimgurl());
                m.setSubscribe(wx.getSubscribe());
                m.setSubscribe_time(wx.getSubscribe_time());
                m.setCountry(wx.getCountry());
                m.setStatus(BuzConst.WX_GUANZHU);

                //            m.setUpdateTime(DateUtils.getCurrDate(null)); 
                currentSession.update(m);
            }
            tx.commit();
        }
        catch (Exception e)
        {
            log.debug("同步出现异常："+e);
            tx.rollback();
        }
        currentSession.close();
    }

    public void regist(Thread t)
    {
        synchronized (runningThreads)
        {
            runningThreads.add(t);
        }
    }

    public void unRegist(Thread t)
    {
        synchronized (runningThreads)
        {
            runningThreads.remove(t);
            c++;
        }
    }

    public static boolean hasThreadRunning()
    {
        return (runningThreads.size() > 0);//通过判断runningThreads是否为空就能知道是否还有线程未执行完  
    }

    public String getToken()
    {
        return token;
    }

    public void setToken(String token)
    {
        this.token = token;
    }

    public String getOpenId()
    {
        return openId;
    }

    public void setOpenId(String openId)
    {
        this.openId = openId;
    }

    public static int getC()
    {
        return c;
    }

    public static void setC(int c)
    {
        SynWxInfoThread.c = c;
    }

    public static int getProcess()
    {
        return 100 * c / total;
    }

    public Session getCurrentSession()
    {
        return currentSession;
    }

    public void setCurrentSession(Session currentSession)
    {
        this.currentSession = currentSession;
    }

}
